import { Component, Injector } from '@angular/core';
import { AppComponentBase } from '@shared/common/app-component-base';
import { GetNodeListDto, GetNodeListType, NameValue, UnitSelectionData, UserSelectionData, WorkFlowServiceProxy } from '@shared/service-proxies/service-proxies';
import { BsModalRef } from 'ngx-bootstrap/modal';
import { merge as _merge } from 'lodash-es';
import { finalize } from 'rxjs/operators';
import { UserHelper } from '@app/shared/common/workflow/user-helper.service';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';

export interface IUserSelectionOptions {
    modalTitle: string;
    paperId: string;
    actionName: string;
    type: GetNodeListType;
    isRequired: boolean;
    nodeId: string;
}

@Component({
    templateUrl: './user-selection-modal.component.html',
})
export class UserSelectionModelComponent extends AppComponentBase {

    options: IUserSelectionOptions;

    callback: {(data:any):void};

    title: SafeHtml = '';

    isShown = false;
    isInitialized = false;

    loading = false;
    saving = false;

    unitList:UnitSelectionData[] = [];
    userList:UserSelectionData[] = [];
    allUserList:UserSelectionData[] = [];

    selectionUserList:UserSelectionData[] = [];
    nodeList:GetNodeListDto[]  = [];
    actionSchemeList:NameValue[]  = [];

    selectUnitId:string = '';

    selection = {
        selectNodeId: "",
        selectUserIdList: [],
        selectActionScheme: '3'
    };

    constructor(
        injector: Injector,
        public bsModalRef: BsModalRef,
        protected dom: DomSanitizer,
        private _workFlowServiceProxy:WorkFlowServiceProxy,
        private _userHelper:UserHelper
    ) {
        super(injector);
    }

    close(): void {
        this.bsModalRef.hide();
    }

    shown(options: IUserSelectionOptions): void {
        this.options = options;
        this.title = this.dom.bypassSecurityTrustHtml(this.options.modalTitle);

        this.isShown = true;
        
        this.getNodeList();

        this.isInitialized = true;
    }

    private getUnitTree(items) {
        for (var i = 0, len = items.length; i < len; i++) {
            var blank = "";
            for (var j = 0, len_j = items[i].level; j < len_j; j++) {
                blank += "　　";
            }
            items[i].displayName = blank + "┠" + items[i].name;
        }
    }

    getUserList(selectNodeId) {
        this.loading = true;
        this._workFlowServiceProxy.getUserList(this.options.paperId, selectNodeId, undefined, this.options.actionName)
            .pipe(finalize(() => { this.loading = false; }))
            .subscribe(result => {
                this.unitList = result.units;
                this.getUnitTree(this.unitList);
    
                let selectdUsers = [];
                
                this.userList = result.users;
                this.allUserList = result.users;
                if (result.defaultSelectedUsers && result.defaultSelectedUsers.length > 0) {
                    selectdUsers = result.defaultSelectedUsers;
                    this._userHelper.userSort(selectdUsers);
                    //bubbleSort(vm.selectionUserList);
                }
                this.selectionUserList = selectdUsers;
                this.actionSchemeList = result.actionSchemeList;
                this.selection.selectActionScheme = result.actionScheme.toString();
            });
    };

    getNodeList () {
        this.loading = true;
        this._workFlowServiceProxy.getNodeList(this.options.paperId, this.options.type )
        .pipe(finalize(() => { this.loading = false; }))
        .subscribe((result) =>{
            let selectedNodeId, i;
            this.nodeList = result.nodeList;
            
            if (this.nodeList.length > 0) {
                selectedNodeId = this.nodeList[0].value;
                for (i = 0; i < this.nodeList.length; i++) {
                    if (this.nodeList[i].defaultSelected) {
                        selectedNodeId = this.nodeList[i].value;
                    }
                }
                this.selection.selectNodeId = selectedNodeId;
                this.getUserList(selectedNodeId);
            }
        });
    };

    changeNode () {
        if (!this.selection.selectNodeId) return;
        this.getUserList(this.selection.selectNodeId);
    };

    selectUsers (item) {
        for (let i = 0; i < this.selectionUserList.length; i++) {
            if (this.selectionUserList[i].id === item.id) {
                return;
            }
        }

        this.selectionUserList.push(item);
        //排序
        this._userHelper.userSort(this.selectionUserList);
    };

    removeSelectUsers(item) {
        if (item.required) {
            this.notify.warn(item.surname + "是必选项，不能移除");
            return;
        }

        let i = -1;
        this.selectionUserList.forEach( (value, index)=> {
            if (value.id === item.id) {
                i = index;
            }
        });
        if (i > -1) {
            this.selectionUserList.splice(i, 1);
        }
    };

    changeUnit() {
        if (!this.selectUnitId) {
            this.userList = this.allUserList;
            return;
        }
        this.userList = [];
        this.allUserList.forEach((value, index) => {
            value.units.forEach((k, j) =>{
                if (k.id.toString() == this.selectUnitId) {
                    if (this.userList.indexOf(value) < 0) {
                        this.userList.push(value);
                    }
                }
            });
        });
    };


    save() {
        this.selectionUserList.forEach((value, index)=> {
            this.selection.selectUserIdList.push(value.id);
        });

        if (this.options.isRequired) {
            if (!this.selection.selectNodeId 
                || this.selection.selectUserIdList.length === 0 
                || !this.selection.selectActionScheme) {
                return;
            }
        }

        this.callback(this.selection);
        this.close();
    }
}
